import hashlib
import os
from webExcel import settings
from apps.base_data.models import User
import time
import pandas


class MD5:
    @staticmethod
    def de(string):
        hl = hashlib.md5()
        hl.update(string.encode(encoding='utf-8'))
        return hl.hexdigest().upper()


class FileUtil:
    @staticmethod
    def get_size(dir_name):
        path = settings.BASE_DIR + settings.USER_FILE_SAVE_PATH + \
               str(dir_name.replace('@', '.'))
        return FileUtil.getdirsize(path)

    @staticmethod
    def getdirsize(dir):
        size = 0
        for root, dirs, files in os.walk(dir):
            size += sum([os.path.getsize(os.path.join(root, name))
                         for name in files])
        return size

    @staticmethod
    def get_file_count(dir_name):
        return len(FileUtil.get_file_list(dir_name))

    @staticmethod
    def get_file_list(dir_name):
        path = settings.BASE_DIR + settings.USER_FILE_SAVE_PATH + \
               str(dir_name.replace('@', '.'))
        return os.listdir(path)

    @staticmethod
    def get_files_info(dir_name):
        res = []
        path = settings.BASE_DIR + settings.USER_FILE_SAVE_PATH + \
               str(dir_name.replace('@', '.'))
        for name in os.listdir(path):
            fn = os.stat(path + os.sep + name)
            # 最后一次访问时间
            st_atime = time.strftime(
                "%Y-%m-%d %H:%M:%S", time.localtime(fn.st_atime))
            # 最后一次修改时间
            st_mtime = time.strftime(
                "%Y-%m-%d %H:%M:%S", time.localtime(fn.st_mtime))
            # 最后一次状态变化的时间
            st_ctime = time.strftime(
                "%Y-%m-%d %H:%M:%S", time.localtime(fn.st_ctime))
            res.append({
                'name': name,
                'st_size': fn.st_size,
                'st_atime': st_atime,
                'st_mtime': st_mtime,
                'st_ctime': st_ctime,
            })
        return res

    @staticmethod
    def file_iterator(file_name, chunk_size=512):
        with open(file_name, 'rb') as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    @staticmethod
    def get_file_stream(dir_name, filename):
        path = settings.BASE_DIR + settings.USER_FILE_SAVE_PATH + \
               str(dir_name.replace('@', '.')) + os.sep + filename
        return FileUtil.file_iterator(path)

    @staticmethod
    def write_file(dir_name, filename, data):
        path = settings.BASE_DIR + settings.USER_FILE_SAVE_PATH + \
               str(dir_name.replace('@', '.')) + os.sep + filename
        with open(path, 'w') as f:
            for i in data:
                f.write('\t'.join(i))
                f.write('\n')

    @staticmethod
    def create(dir_name, filename):
        path = settings.BASE_DIR + settings.USER_FILE_SAVE_PATH + \
               str(dir_name.replace('@', '.')) + os.sep + filename
        flag = os.path.exists(path)
        if flag:
            return flag, 'File already exists'
        with open(path, 'w+') as f:
            f.write('')
        return False, 'Success'

    @staticmethod
    def create_dir(dir_name):
        path = settings.BASE_DIR + settings.USER_FILE_SAVE_PATH + \
               str(dir_name.replace('@', '.'))
        os.makedirs(path)

    @staticmethod
    def delete(dir_name, filename):
        path = settings.BASE_DIR + settings.USER_FILE_SAVE_PATH + \
               str(dir_name.replace('@', '.')) + os.sep + filename
        os.remove(path)


class ModelUtil:
    @staticmethod
    def get_user(email) -> User:
        user = User().orm.find().where(email=email).end()
        if user:
            return user.first()
        return None

    @staticmethod
    def read_csv(dir_name, filename):
        path = settings.BASE_DIR + settings.USER_FILE_SAVE_PATH + \
               str(dir_name.replace('@', '.')) + '/' + filename
        return pandas.read_csv(path, delim_whitespace=True, header=0)
